/**
 * @Title: stationController.java
 * @Package tt.dz.mvc.controller.sys
 * @author pengyu
 * @date 2015年12月17日 上午10:21:55
 * @version V1.0
 */
package tt.dz.mvc.controller.sys;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.web.session.HttpServletSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import tt.dz.dao.ext.system.OmsOperationSpListDao;
import tt.dz.entity.base.JsonCommon;
import tt.dz.entity.base.JsonForList;
import tt.dz.entity.base.OmsCommonParam;
import tt.dz.entity.base.OmsEntityEnum;
import tt.dz.entity.exception.BizException;
import tt.dz.entity.exception.OmsDaoException;
import tt.dz.entity.system.OmsOperList;
import tt.dz.entity.system.OmsOperationSpList;
import tt.dz.entity.system.OmsUrlList;
import tt.dz.mvc.controller.base.BaseAction;
import tt.dz.mvc.controller.base.BaseController;
import tt.dz.mvc.model.AddUserModel;
import tt.dz.mvc.model.AddUserRolesModel;
import tt.dz.mvc.model.UpdatePwdModel;
import tt.dz.mvc.model.UpdateUserModel;
import tt.dz.service.sys.RoleService;
import tt.dz.service.sys.OperListService;
import tt.dz.tcp.rpc.ms.SystemMasterServerRpcClient;
import tt.dz.tcp.rpc.ms.client.entity.MasterQueryUserParam;
import tt.dz.tcp.rpc.ms.client.entity.MasterQueryUserReturn;
import tt.dz.util.ActionUtils;
import tt.dz.util.OmsConstant;
import tt.dz.util.OmsConstant.MsgCodeEnum;
import tt.dz.util.StringUtil;

@Controller
@RequestMapping("userApi")
public class OperListController extends BaseController
{
	private Log log = LogFactory.getLog(OperListController.class);

	@Autowired
	@Qualifier(value="operatorService")
	private OperListService  operatorServiceImpl;
	@Autowired
	@Qualifier(value="roleServiceImpl")
	private RoleService  roleServiceImpl;
	@Autowired
	@Qualifier(value="omsOperationSpListDao")
	private OmsOperationSpListDao  omsOperationSpListDao;
	@Autowired
	private SystemMasterServerRpcClient msClient;

	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	public JsonCommon<OmsOperList> login(HttpServletRequest request) throws BizException
	{
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		OmsOperList oper = operatorServiceImpl.login(account, password);
		if (oper == null)
			throw new BizException("Login failed");

		HttpSession session = request.getSession();
		session.invalidate();

		HttpSession new_session = request.getSession();
		oper.setPassword(null);
		new_session.setAttribute(BaseAction.CommonParam.SESSION_USER, oper);

		new_session.setAttribute("login_oper_id", oper.getOper_id());
		new_session.setAttribute("login_entity_type", String.valueOf(oper.getEntity_type()));
		new_session.setAttribute("login_super_flag", oper.getIsSupper().toString());
//		new_session.setAttribute("change_password", oper.getPwdchg_ind());

		return new JsonCommon(oper, OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}

	@RequestMapping(value = "logout")
	@ResponseBody
	public JsonCommon logout(HttpSession session) throws BizException
	{
		session.invalidate();
		return new JsonCommon(OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}
	
	@RequestMapping(value="getUrlListByLogin",method=RequestMethod.GET)
	@ResponseBody
	public JsonForList<?> getUrlListByLogin(HttpSession session) throws OmsDaoException
	{
		OmsOperList user = (OmsOperList) session.getAttribute(BaseAction.CommonParam.SESSION_USER);
		if(user == null){
			log.error("getUrlListByLogin user null");
			return new JsonForList<>(null, "400", "user null");
		}
		List<OmsUrlList> list_url = operatorServiceImpl.getUrlListByOperId(user.getOper_id());
		return new JsonForList<>(list_url, OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}

	@RequestMapping(value="add",method=RequestMethod.POST)
	@ResponseBody
	public JsonCommon<?> add(@Valid AddUserModel addUserModel, HttpSession session, BindingResult validateresult) throws OmsDaoException
	//	public JsonCommon<?> add(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		log.debug(addUserModel);

		log.debug(validateresult.hasErrors());
		log.debug(validateresult.getAllErrors());

		OmsOperList oper = addUserModel.generateOmsOperList();

		OmsOperList current_user =  (OmsOperList) session.getAttribute(BaseAction.CommonParam.SESSION_USER);
		oper.setCreate_ms_user_id(current_user.getMs_manager_id());
		oper.setCreate_oper_id(current_user.getOper_id());

		String newoperid = operatorServiceImpl.add(oper);
		return new JsonCommon<>(newoperid, OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}
	@RequestMapping(value="update", method=RequestMethod.POST)
	@ResponseBody
	public JsonCommon<?> update(@Valid UpdateUserModel updateUserModel, HttpSession session) throws Exception {
		OmsOperList oper = updateUserModel.generateOmsOperList();
		OmsOperList current_user =  (OmsOperList) session.getAttribute(BaseAction.CommonParam.SESSION_USER);
		operatorServiceImpl.update(oper, current_user);
		return new JsonCommon<>(OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}
	
	@RequestMapping(value="logicalDel",method=RequestMethod.POST)
	@ResponseBody
	public JsonCommon<?> logicalDel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String oper_id = request.getParameter("oper_id");
		return operatorServiceImpl.deleteLogical(oper_id);
	}
	
	@RequestMapping(value="findAllOrPage",method=RequestMethod.GET)
	@ResponseBody
	public JsonForList<?> findAllOrPage(HttpServletRequest request, HttpServletResponse response)
	{
		OmsOperList oper = genarateObj(request, getLoginUserId(request), false,true);
		OmsOperList user = this.getLoginUser(request);
		
		return operatorServiceImpl.findPageObjs(this.buildQueryParam(request, true), oper, user.getIsSupper() > 0 ? OmsEntityEnum.SUPER_OPERMERCHANT.getValue() : user.getEntity_type(), user.getEntity_id());
	}
	
	@RequestMapping(value="findUserFiles",method=RequestMethod.GET)
	@ResponseBody
	public JsonForList<?> findUserFiles(HttpServletRequest request, HttpServletResponse response)
	{
		OmsOperList user = this.getLoginUser(request);
		return operatorServiceImpl.findUserStoreFiles(user);
	}

	@RequestMapping(value = "updatePwd", method = RequestMethod.POST)
	@ResponseBody
	public JsonCommon updatePwd(@Valid UpdatePwdModel model, HttpSession session) throws BizException
	{
		OmsOperList current_user = (OmsOperList) session.getAttribute(BaseAction.CommonParam.SESSION_USER);
		if(!model.getNewPwd().equals(model.getRepeatNewPwd()))
			throw new BizException("重复的密码不相同");
		if(model.getNewPwd().equals(model.getOldPwd()))
			throw new BizException("新的密码不能与原有密码相同");
		operatorServiceImpl.updatePwd(current_user, model.getOldPwd(), model.getNewPwd());
		return new JsonCommon(OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}
	
	private OmsOperList genarateObj(HttpServletRequest request,String userId,boolean isCreate,boolean isFind)
	{
		Map<String,String> params = ActionUtils.getParameterMap(request);
		return ActionUtils.getParamInstance(OmsOperList.class, params, userId, isCreate, isFind);
	}
	
	@RequestMapping(value="findExistRolesByOperId",method=RequestMethod.GET)
	@ResponseBody
	public JsonForList<?> findExistRolesByOperId(HttpServletRequest request, HttpServletResponse response) throws Exception 
	{
		String operId = request.getParameter("operId");//ms_manager_id 主服务管理员id
		return roleServiceImpl.findExistRolesByOperId(operId);
	}
	
	@RequestMapping(value="findCanbindRolesByOperId",method=RequestMethod.GET)
	@ResponseBody
	public JsonForList<?> findCanbindRolesByOperId(HttpServletRequest request, HttpServletResponse response) throws Exception 
	{
		String operId = request.getParameter("operId");//ms_manager_id 主服务管理员id
		String entityId = request.getParameter("entityId");
		String entityType = request.getParameter("entityType");
		return roleServiceImpl.findCanbindRolesByOperId(operId, entityId, entityType);
	}

	@RequestMapping(value = "addUserRoles", method = RequestMethod.POST)
	@ResponseBody
	public JsonCommon<?> addUserRoles(@Valid AddUserRolesModel addUserRolesModel, HttpSession session) throws Exception
	{
		List<String> list_roleId = JSON.parseArray(addUserRolesModel.getRoleIds(), String.class);
		OmsOperList current_user = (OmsOperList) session.getAttribute(BaseAction.CommonParam.SESSION_USER);
		operatorServiceImpl.assignRolesToUser(addUserRolesModel.getOperId(), list_roleId.toArray(new String[list_roleId.size()]), current_user);
		return new JsonCommon<>(OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}

	@RequestMapping(value = "getCurrentLoginUser", method = RequestMethod.GET)
	@ResponseBody
	public JsonCommon<?> getCurrentLoginUser(HttpServletRequest request) throws Exception
	{
		HttpSession session = request.getSession();
		OmsOperList omsOperList = (OmsOperList) session.getAttribute(BaseAction.CommonParam.SESSION_USER);
		Map<String, Object> pojo = new HashMap<>();

		pojo.put("currentLoginUser", omsOperList);
		pojo.put("loginSuperFlag", omsOperList.getIsSupper());
		return new JsonCommon(pojo, OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}

	@RequestMapping(value = "retrieveAllCompanyUser", method = RequestMethod.GET)
	@ResponseBody
	public JsonForList<MasterQueryUserReturn.MSUser> retrieveAllCompanyUser() throws IOException
	{
		MasterQueryUserParam p = new MasterQueryUserParam();
		p.setUser_type(1);
		MasterQueryUserReturn ret = msClient.queryUser(p);
		return new JsonForList(ret.getResult(), OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}

	private OmsOperList getLoginUser(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		return (OmsOperList) session.getAttribute(BaseAction.CommonParam.SESSION_USER);
	}


	private String getLoginUserId(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		return (String) session.getAttribute(BaseAction.CommonParam.SESSION_USERID);
	}

	private OmsCommonParam buildQueryParam(HttpServletRequest request,boolean isQueryTotal)
	{
		OmsCommonParam returnParam = new OmsCommonParam();
		returnParam.setQueryTotal(isQueryTotal);
		returnParam.setSortName(request.getParameter(BaseAction.CommonParam.SORT_NAME));
		String sortValue = request.getParameter(BaseAction.CommonParam.SORT_VALUE);
		String pageNo = request.getParameter(BaseAction.CommonParam.PAGE_NO);
		String pageSize = request.getParameter(BaseAction.CommonParam.PAGE_SIZE);
		if (StringUtils.isNumeric(sortValue))
		{
			returnParam.setSortValue(Integer.parseInt(sortValue));
		}

		if (StringUtils.isNumeric(pageNo) && StringUtils.isNumeric(pageSize))
		{
			returnParam.setPageNo(Integer.parseInt(pageNo));
			returnParam.setPageSize(Integer.parseInt(pageSize));
		}

		return returnParam;
	}
}
